package com.ld.security.common.shiro.Interceptor;

import com.ld.security.common.core.exception.ApiException;
import com.ld.security.common.shiro.anno.IgnoreUserToken;
import com.ld.security.common.shiro.constants.ShiroCacheConstants;
import com.ld.security.common.shiro.util.SessionUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor extends BaseInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof  HandlerMethod){
            IgnoreUserToken annotation = this.getAnno(handler,IgnoreUserToken.class);
            if(annotation != null){
                return true;
            }
        }


        Subject subject =  SecurityUtils.getSubject();
        Session session = subject.getSession();

        String id =(String) subject.getSession().getId();
        if(subject.isAuthenticated()){
            Boolean kickout = (Boolean) SessionUtil.get(ShiroCacheConstants.kickoutKey);

            if(kickout != null && kickout){
                subject.logout();
                ApiException.throw401("你被下线");

            }
        }else{
            ApiException.throw401("请登录后再访问");

        }

        return true;
    }

    @Override
    public String getName() {
        return "login";
    }
}
